<?php

initial();
global $conn;
switch ($_SERVER['REQUEST_METHOD']) {//根据不同的请求方式进行不同操作，GET通常为页面，POST通常为数据处理
    case "GET":
        _get();
        break;
    case "POST":
        _post();
        break;
    default:
        debugMessage("留言板", "不支持的请求方式“" . $_SERVER['REQUEST_METHOD'] . "”", true);
}

function _get()
{
    define("location", getPath());
    switch (getPath()) {
        case "/":
            get::root();
            break;
        case "/language":
            get::language();
            break;
        case "/login":
            get::login();
            break;
        case "/register":
            get::register();
            break;
        case "/main":
            get::main();
            break;
        case "/logoff":
            get::logoff();
            break;
        case "/phpinfo":
            phpinfo();
            die();
        case "/choose_room":
            get::choose_room();
            break;
        case "/goto_room":
            get::goto_room();
            break;
        case "/back_room":
            get::back_room();
            break;
        case "/dev":
            $text = "hello world";
            echo $text . " 的翻译结果为：" . fanyi::fy($text);
            die();
        case "/install":
            installer::install();
            break;
    }
}

function _post()
{
    switch (getPath()) {
        case "/login":
            post::login();
            break;
        case "/register":
            post::register();
            break;
        case "/getCAPTCHA":
            post::getCAPTCHA();
            break;
        case "/getRoomInfo":
            post::getRoomInfo();
            break;
        case "/getMessageList":
            post::getMessageList();
            break;
        case "/snt":
            post::snt();
            break;
        case "/dz":
            post::dz();
            break;
        case "/del":
            post::del();
            break;
        case "/editMessage":
            post::editMessage();
            break;
        case "/saveRoomName":
            post::saveRoomName();
            break;
        case "/saveRoomDescription":
            post::saveRoomDescription();
            break;
        case "/install":
            installer::install();
            break;
    }
}

function getPath()
{
    $a = "/";
    if (isset($_SERVER['QUERY_STRING'])) {
        $a = $_SERVER['QUERY_STRING'];
    }
    $b = stripos($a, "&");
    $C = "";
    if ($b != "") {
        $c = substr($a, 0, $b);
    } else {
        $c = $a;
    }
    if ($c == "") {
        $c = "/";
    }
    if (substr($c, strlen($c) - 1, 1) == "/") {
        $c = substr($c, 0, strlen($c) - 1);
    }
    if ($c == "") {
        $c = "/";
    }
    return $c;
}

function genXCID($return = false)
{
    $v1 = time();
    $v2 = rand(0, 100);
    $v3 = dechex($v2);
    $v4 = $v1 . $v3 . $v2;
    $v5 = hash("sha256", $v4);
    $v6 = substr($v5, 0, 8);
    if ($return) {
        return $v6;
    } else {
        echo $v6;
    }
}

function connectDB()
{
    $sconfig = file_get_contents(SYSTEM_CONFIG_PATH . "not_connect_db.json");
    $scjson = json_decode($sconfig, true);
    if (in_array(getPath(), $scjson)) {
        return;
    }
    $config = file_get_contents(CONFIG_PATH . "db_config.json");
    $json = json_decode($config, true);
    $host = $json['host'];
    $user = $json['user'];
    $pwd = $json['pwd'];
    $name = $json['name'];
    $port = $json['port'];
    $conn = mysqli_connect($host, $user, $pwd, $name, $port);
    if (!$conn) {
        debugMessage("数据库", "数据库连接失败：" . mysqli_connect_error(), true);
    }
    if (!mysqli_query($conn, "set names utf8mb4")) {
        debugMessage("数据库", "数据库执行失败：" . mysqli_error($conn), true);
    }
//    debugMessage("数据库", "数据库连接成功");
    $GLOBALS['conn'] = $conn;
}

function debugMessage($prefix, $message, $die = false)
{
    $tmp_message = "[" . date("H:i:s") . " " . $prefix . "] " . $message . "<br>";
    if ($die) {
        die($tmp_message);
    } else {
        echo($tmp_message);
    }
}

function initial()
{
    if (!file_exists(INSTALLER_PATH . "installed.lck") && getPath() != "/install") {
        header("Location:./?/install");
    }
    if (file_exists(INSTALLER_PATH . "installed.lck") && getPath() == "/install") {
        header("Location:./?/");
    }
    include(CHAT_PATH . "get.php");
    include(CHAT_PATH . "post.php");
    include(CHAT_PATH . "loadStatic.php");
    include(CHAT_PATH . "arrayTool.php");
    include(CHAT_PATH . "stringTool.php");
    include(CHAT_PATH . "fanyi.php");
    include(CHAT_PATH . "dbTool.php");
    if (getPath() == "/install") {
        include(INSTALLER_PATH . "installer.php");
    }
    $GLOBALS['loadStatic'] = new loadStatic();
    date_default_timezone_set("PRC");
    connectDB();
}

function loadHead($title)
{
    echo str_replace("{title}",$title,str_replace("{language}",cookie::get("local_language"),file_get_contents(HTML_PATH . "head.html")));
}

function loadNav()
{
    loadStatic::html('nav');
}

function loadLanguageList()
{
    for ($i = 0; $i < count(LANGUAGE_LIST); $i++) {
        echo '<li><a href="./?/language&set=' . array_keys(LANGUAGE_LIST)[$i] . '&from=' . location . (isset($_GET['step'])?(',step='.$_GET['step']):'').'">' . LANGUAGE_LIST[array_keys(LANGUAGE_LIST)[$i]] . '</a></li>';
    }
}

function loadFriendLinks()
{
    if (file_exists(CONFIG_PATH . "friend_links.json")) {
        $a = file_get_contents(CONFIG_PATH . "friend_links.json");
        $b = json_decode($a, true);
        foreach (array_keys($b) as $x) {
            $t = $b[$x];
            $target = "";
            switch ($t['openWay']) {
                case "this":
                case "thisTab":
                case "self":
                    $target = "_self";
                    break;
                case "parent":
                    $target = "_parent";
                    break;
                case "top":
                    $target = "_top";
                    break;
                case "new":
                case "newTab":
                case "blank":
                default:
                    $target = "_blank";
                    break;
            }
            if (!(isset($t['hide']) && $t['hide'])) {
                echo("<li><a target='$target' href='" . $t['link'] . "'>" . $t['name'] . "</a></li>");
            }
        }
    }
}

function xc_mail($address, $subject, $body)
{
    $result = array();
    $wait_time = 180;
    if (time() - cookie::get('send_mail_time') < $wait_time) {
        $a = time();
        $b = cookie::get('send_mail_time');
        $c = $wait_time - (time() - cookie::get('send_mail_time'));
        $result['status'] = "send_wait";
        $result['wait_time'] = $c;
        return $result;
    }
    require './system/core/mail/PHPMailerAutoload.php';
    $config = json_decode(file_get_contents(CONFIG_PATH . "mail_config.json"), true);
    $mail = new PHPMailer(false);
    $mail->isSMTP();
    $mail->Host = $config['mail_smtp'];
    $mail->SMTPAuth = true;
    $mail->Username = $config['mail_username'];
    $mail->Password = $config['mail_password'];
    $mail->setFrom($config['mail_username'], ROOT_TITLE);
    $mail->addAddress($address);
    $mail->CharSet = 'UTF-8';
    $mail->Subject = $subject;
    $mail->Body = '<div style="width: 85%;height: 50%;padding: 15px;background-color: #3280fc;color: #FFFFFF;box-shadow: 10px 10px 5px grey;font-size: 25px">' . $body . '</div>';
    $mail->AltBody = MAIL_ALTBODY;
    if ($mail->send()) {
        cookie::set("send_mail_time", time());
        $result['status'] = "successful";
    } else {
        $result['status'] = "fail";
        $result['reason'] = $mail->ErrorInfo;
    }
    return $result;
}

function getRoomXCID($return = false)
{
    $a = cookie::get('room_xcid');
    if (!$a) {
        $a = "chat";
    }
    if ($a != "chat") {
        $a = "room_" . $a;
    }
    if ($return) {
        return $a;
    } else {
        echo $a;
    }
}

function updateLoginStatus()
{
    if (cookie::get('isLogin') == "yes") {
        $username = cookie::get('username');
        $password = cookie::get('password-part1') . cookie::get('password-part2') . cookie::get('password-part3') . cookie::get('password-part4');
        $conn = $GLOBALS['conn'];
        $result = mysqli_query($conn, "SELECT * FROM user");
        if (!$result) {
            header("Location:./?/");
        }
        while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
            if ($row['username'] == $username || $row['email'] == $username) {
                if ($row['password'] == $password) {
                    if ($row['is_ban'] == "yes") {
                        header("Location:./?/logoff");
                    } else {
                        cookie::set("isLogin", "yes")
                            ->set("username", $username)
                            ->set("nickname", $row['nickname'])
//                            ->set("room_xcid", "chat")
                            ->set("password-part1", substr($password, 0, 20))
                            ->set("password-part2", substr($password, 20, 20))
                            ->set("password-part2", substr($password, 20, 20))
                            ->set("password-part3", substr($password, 40, 20))
                            ->set("password-part4", substr($password, 60, 4))
                            ->set("isAdmin", $row['is_admin']);
                        return;
                    }
                } else {
                    header("Location:./?/logoff");
                }
            }
        }
        header("Location:./?/logoff");
    }
}